package com.ardf.service.impl;

import com.alibaba.excel.EasyExcel;
import com.ardf.entity.Athlete;
import com.ardf.entity.Group;
import com.ardf.entity.Number;
import com.ardf.entity.dto.DownloadNumberDto;
import com.ardf.entity.dto.NumberSearchAllDto;
import com.ardf.mapper.AthleteMapper;
import com.ardf.mapper.GroupMapper;
import com.ardf.mapper.NumberMapper;
import com.ardf.service.INumberService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ShiYunHao
 * @since 2025-01-06
 */
@Service
public class NumberServiceImpl extends ServiceImpl<NumberMapper, Number> implements INumberService {

    private final NumberMapper numberMapper;
    private final GroupMapper groupMapper;
    private final AthleteMapper athleteMapper;
    public NumberServiceImpl(NumberMapper numberMapper,GroupMapper groupMapper,AthleteMapper athleteMapper){
        this.numberMapper=numberMapper;
        this.groupMapper= groupMapper;
        this.athleteMapper=athleteMapper;
    }

    @Override
    public Page<NumberSearchAllDto> searchAll(Integer pageSize, Integer pageNum, Long competitionId, String searchAll) {
        Page<NumberSearchAllDto> page = new Page<>(pageNum,pageSize);
        return numberMapper.searchAll(page, competitionId, searchAll);
    }

    @Override
    public Boolean containsEmpty(Long competitionId) {
        List<Number> numbers = numberMapper.containsEmpty(competitionId);
        if (numbers.size()>0) return true;
        else return false;
    }

    @Override
    @Transactional
    public void oneClick(Long competitionId) {
        List<Group> groups = groupMapper.selectList(new LambdaQueryWrapper<Group>()
                .eq(Group::getCompetitionId, competitionId));
        List<Long> groupCount = groups.stream().map(group ->
                athleteMapper.selectCount(new LambdaQueryWrapper<Athlete>()
                .eq(Athlete::getGroupId, group.getId()))).toList();
        Optional<Long> max = groupCount.stream().max(Long::compareTo);
        int size=4;
        if (max.isPresent()) {
            //size=String.valueOf(max.get()).length();
            for (Group group : groups) {
                List<Number> numbers=numberMapper.listByGroupId(group.getId());
                long num=0;
                for (Number number : numbers) {
                    number.setNumber(group.getName()+"-"+String.format("%0" + size + "d", num));
                    num++;
                }
                //批量更新
                numberMapper.updateById(numbers);
            }
        }
    }

    @Override
    public boolean check(Long competitionId, String number,Long numberId) {
        return numberMapper.check(competitionId, number,numberId) == 0;
    }

    @Override
    public void download(HttpServletResponse response,Long competitionId) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("选手号码表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<DownloadNumberDto> list=numberMapper.getAll(competitionId);
        EasyExcel.write(response.getOutputStream(), DownloadNumberDto.class).sheet("表格1").doWrite(list);
    }
}
